import axios, { AxiosRequestConfig, AxiosError } from 'axios';
import router from "@/route";
import { getBaseHeader } from '@/utils/utils';
import defaultConfig from '@/ajax/defaultConfig';
const BASEURL = defaultConfig.baseURL + 'api/';
import { Modal } from 'ant-design-vue';
function message(content: string, title: string = '系统提示') {
  Modal.error({
    centered: true,
    title,
    content,
    mask: true,
    okText: '确定',
  });
}
/**
 *@name $axios 使用该对象的方法需要传入完整的接口地址
 */
export const $axios = axios.create({
  timeout: 20000,
  validateStatus: (statusCode: number): boolean => {
    return statusCode == 200;
  },
});
$axios.interceptors.request.use(async (config: any) => {
  // 配置headers
  const tempHeaders = getBaseHeader();

  config.headers = {
    ...config.headers,
    ...tempHeaders,
  };
  return config;
});
$axios.interceptors.response.use(
  (response) => {
    return response.data;
  },
 async (e: AxiosError) => {
    if (navigator.onLine) {
      if (e?.response) {
        const { status } = e.response;
        let msg = '';
        if (e.response.data) {
          msg = e.response.data.msg;
        }
        switch (status) {
          case 400:
            message(msg || '参数错误，无法完成请求');
            break;
          case 401:
            message('登录过期，请重新登录');
            await router.replace('/home')
            location.reload()
            break;
          case 404:
            message('404NotFind');
            break;
          case 500:
            break;
          case 502:
            message('服务器无法完成响应');
            break;
          default:
            message(e.message);
            break;
        }
      } else if (e.message.includes('timeout')) {
        message('请求服务器超时');
      } else {
        message('未知的原因导致请求失败！');
      }
    } else {
      message('请检查设备网络');
    }

    return Promise.reject(e);
  }
);

/** @name BaseOperator  接口调用成功后返回的操作员和操作时间  */
export interface BaseOperator {
  lastUpdated: string;
  updatedBy: string;
}
/** @name BaseResponse  接口的返回值  */
export interface BaseResponse<T = any> {
  /** @name code 后台返回状态码 */
  code: number;
  /** @name msg 后台传入消息，失败时需显示 */
  msg: string;
  /** @name data 成功后的数据 */
  data?: T;
  operator: BaseOperator;
  /** @name data 成功后的数据 */
}

/**
 * @name 初始化GET请求方法
 * @param {string} commonUrl:公共的路径
 */
export function InitGet(commonUrl: string = '') {
  return function GET<T = any>(
    config: AxiosRequestConfig = {},
    baseURL: string = BASEURL + commonUrl
  ): Promise<BaseResponse<T>> {
    // get方法传入data无效。将其替换为params
    if (config.data) {
      config.params = config.data;
    }
    return new Promise((resolve, reject) => {
      $axios
        .get<T, BaseResponse<T>>(baseURL + (config?.url || ''), config)
        .then((response) => {
          if (response.code != 200) {
            return reject(response);
          }
          resolve(response);
        })
        .catch((e) => reject(e));
    });
  };
}
/**
 * @name 初始化POST请求方法
 * @param {string} commonUrl:公共的路径
 */
export function InitPost(commonUrl = '') {
  return function POST<T = any>(
    data: any,
    baseURL: string = BASEURL + commonUrl,
    config: AxiosRequestConfig = {}
  ): Promise<BaseResponse<T>> {
    return new Promise((resolve, reject) => {
      $axios
        .post<T, BaseResponse<T>>(baseURL + (config?.url || ''), data, config)
        .then((response) => {
          if (response.code != 200) {
            requstErrorhandle(response);
            return reject(response);
          }
          resolve(response);
        })
        .catch((e) => {
          requstErrorhandle({});
          reject(e);
        });
    });
  };
}
/**
 * @name 初始化PUT请求方法
 * @param {string} commonUrl:公共的路径
 */
export function InitPut(commonUrl = '') {
  return function PUT<T = any>(
    data: any,
    baseURL: string = BASEURL + commonUrl,
    config: AxiosRequestConfig = {}
  ): Promise<BaseResponse<T>> {
    return new Promise((resolve, reject) => {
      $axios
        .put<T, BaseResponse<T>>(baseURL + (config?.url || ''), data, config)
        .then((response) => {
          if (response.code != 200) {
            return reject(response);
          }
          resolve(response);
        })
        .catch((e) => {});
    });
  };
}
/**
 * @name 初始化DELETE请求方法
 * @param {string} commonUrl:公共的路径
 */
export function InitDelete(commonUrl = '') {
  return function DELETE<T = any>(
    config: AxiosRequestConfig = {},
    baseURL: string = BASEURL + commonUrl
  ): Promise<BaseResponse<T>> {
    return new Promise((resolve, reject) => {
      $axios
        .delete<T, BaseResponse<T>>(baseURL + (config?.url || ''), config)
        .then((response) => {
          if (response.code != 200) {
            return reject(response);
          }
          resolve(response);
        })
        .catch((e) => reject(e));
    });
  };
}
/**
 * @name 请求异常处理
 */
function requstErrorhandle(error: AnyObj) {
  // if(error.status){
  //   // 接口没通
  //   if(error.status){
  //   }
  // }
  // // 接口通了，但是没成功
  // if(error.msg){
  //   // error.msg
  //   // 接口没通
  //   //
  // }
}
